package com.example.demo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.springframework.core.io.ClassPathResource;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

public class Utils {
    
    public static String getFileSuffix(String fileName){
        String fileSuffix;
        if(fileName.lastIndexOf(".")==-1){fileSuffix="";}
        else{fileSuffix=fileName.substring(fileName.lastIndexOf(".")+1);}
        return fileSuffix;
    }
    public static String getUrlEncode(String fileName){
        String fileNameEncode;
        try {
            fileNameEncode = URLEncoder.encode(fileName,"UTF-8");
            //替换+号否则空格解析会出错            
            fileNameEncode = fileNameEncode.replaceAll("\\+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            fileNameEncode = "";
        }
        return fileNameEncode;
    }
    public static void WordToPdf(String sourcePath,String targetPath) throws Exception {
        FileOutputStream os = null;
        Boolean license = false;
        try {
            System.out.println(sourcePath+" -----> "+targetPath);
            //凭证 不然切换后有水印
            try{
                InputStream is = new ClassPathResource("static/license/license.xml").getInputStream();
                License aposeLic = new License();
                aposeLic.setLicense(is);
                license = true;
            }
            catch(Exception e){
                if (!license) {
                    System.out.println("License验证不通过...");
                }
            }
            //生成一个空的PDF文件
            File file = new File(targetPath);
            os = new FileOutputStream(file);
            //要转换的word文件
            Document doc = new Document(sourcePath);
            doc.save(os, SaveFormat.PDF);
            //去水印慎用 中文会乱码
            // PdfHelper3.removeWatermark(file);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
 
    }
}
